    //
//  ReviewViewController.m
//  Drivers
//
//  Created by Hunk on 10-11-1.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ReviewViewController.h"
#import "ReadFile.h"
#import "WriteFile.h"
#import <AudioToolbox/AudioToolbox.h>

@interface ReviewViewController (Private)

- (void)getQuestion:(int)nQuestionNumber;

- (void)viewFlip:(NSString*)flipMode;

- (void)noWrongQuestion;

- (void)addLabelText:(UILabel*)label labelText:(NSString*)labelText;

@end


#define TITLE_ALERT_HASBEENADDED @"此题已经添加过,请勿重复添加"

#define TITLE_ALERT_FIRSTQUESTION @"这已经是第一题了"

#define TITLE_ALERT_LASTQUESTION @"这已经是最后一题了"

#define FILE_STRENGTHENINGMEMORY @"StrengtheningMemory.sg" // 记录文件路径的文件

#define PLIST_STRENGTHENINGMEMORY @"StrengtheningMemory.plist" // 记录强化记忆题目


@implementation ReviewViewController
@synthesize m_pPrevChooseLabel;
@synthesize m_pRightAnswerLabel;
@synthesize m_pAnswerALabel;
@synthesize m_pAnswerBLabel;
@synthesize m_pAnswerCLabel;
@synthesize m_pAnswerDLabel;
@synthesize m_pPrevButton;
@synthesize m_pNextButton;
@synthesize m_pStrengtheningMemoryButton;
@synthesize m_pImageView;


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad 
{
    [super viewDidLoad];
	
    UIImage *image = [UIImage imageNamed:@"cell_background.png"];
    [_bgImageView setImage:[image stretchableImageWithLeftCapWidth:5 topCapHeight:5]];
    
    [UIView viewLayerCorner:m_pPrevButton];
    [UIView viewLayerCorner:m_pNextButton];
    [UIView viewLayerCorner:m_pStrengtheningMemoryButton];
    
	// Init data
	m_nCurQuestionNumber = 0;
	m_arrayOfStrengtheningMemory = [[NSMutableArray alloc] init];
	
	// Init Question label
	m_pQuestionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 300, 500)];
	m_pQuestionLabel.numberOfLines = 0;
	m_pQuestionLabel.backgroundColor = [UIColor clearColor];	
	m_pQuestionLabel.textColor = [UIColor blackColor];
	m_pQuestionLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:18];
	m_pQuestionLabel.textAlignment = UITextAlignmentLeft;
	[self addLabelText:m_pQuestionLabel labelText:nil];
	[self.view addSubview:m_pQuestionLabel];
	
	// Get wrong questions
	ReadFile* readFile = [[ReadFile alloc] init];
	BOOL bIsFileCanBeOpened = [readFile OpenFile:@"WrongQuestion.sg"];
	if(bIsFileCanBeOpened)
	{
		// Get file path
		NSString* strFilePath = [readFile ReadString];
		
		// Get all wrong questions
		m_arrayOfWrongQuestion = [[NSMutableArray alloc] initWithContentsOfFile:strFilePath];
		
		if(0 == [m_arrayOfWrongQuestion count])
		{
			// Show no question alert
			[self noWrongQuestion];
			
			return;
		}
		
		// Set title
		[self.navigationController.visibleViewController setTitle:[NSString stringWithFormat:@"共%d题,第%d题", [m_arrayOfWrongQuestion count], 1]];
		
		[readFile CloseFile];
		[readFile release];
		
		// Get one question
		[self getQuestion:0];
		
	}
	else
	{
		// Show no question alert
		[self noWrongQuestion];
	}
}

#pragma mark -
#pragma mark Get question
- (void)getQuestion:(int)nQuestionNumber
{
	// Set title
	[self.navigationController.visibleViewController setTitle:[NSString stringWithFormat:@"共%d题,第%d题", [m_arrayOfWrongQuestion count], (nQuestionNumber + 1)]];
	
	// Get the first question from the wrong question array
	NSArray* arrayOfQuestion = [m_arrayOfWrongQuestion objectAtIndex:nQuestionNumber];
	
	// Add label text
	[self addLabelText:m_pQuestionLabel labelText:[arrayOfQuestion objectAtIndex:0]];
	
	//[m_pQuestionLabel setText:[arrayOfQuestion objectAtIndex:0]];
	
	if([arrayOfQuestion count] <= 8 && [arrayOfQuestion count] >= 7)
	{
		m_pAnswerALabel.hidden = NO;
		m_pAnswerBLabel.hidden = NO;
		m_pAnswerCLabel.hidden = NO;
		m_pAnswerDLabel.hidden = NO;
		
		[m_pAnswerALabel setText:[@"A:" stringByAppendingString:[arrayOfQuestion objectAtIndex:1]]];
		[m_pAnswerBLabel setText:[@"B:" stringByAppendingString:[arrayOfQuestion objectAtIndex:2]]];
		[m_pAnswerCLabel setText:[@"C:" stringByAppendingString:[arrayOfQuestion objectAtIndex:3]]];
		[m_pAnswerDLabel setText:[@"D:" stringByAppendingString:[arrayOfQuestion objectAtIndex:4]]];
		[m_pRightAnswerLabel setText:[@"正确答案:" stringByAppendingString:[arrayOfQuestion objectAtIndex:5]]];
		
		[m_pPrevChooseLabel setText:[@"上次所选:" stringByAppendingString:[arrayOfQuestion objectAtIndex:([arrayOfQuestion count]-1)]]];
		
		m_pImageView.alpha = 0.f;
		
		if(8 == [arrayOfQuestion count])
		{
			m_pImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[arrayOfQuestion objectAtIndex:6]]];
			
			float fWidth = m_pImageView.frame.size.width;
			float fHeight = m_pImageView.frame.size.height;
			m_pImageView.alpha = 1.f;
			
			[m_pImageView setFrame:CGRectMake((320 - fWidth)/2, m_pQuestionLabel.frame.size.height + 20, fWidth, fHeight)];
			[self.view addSubview:m_pImageView];
			[m_pImageView release];
		}
	}
	else if([arrayOfQuestion count] < 7)
	{
		m_pAnswerALabel.hidden = YES;
		m_pAnswerBLabel.hidden = YES;
		m_pAnswerCLabel.hidden = NO;
		m_pAnswerDLabel.hidden = NO;
		
		[m_pAnswerCLabel setText:@"正确"];
		[m_pAnswerDLabel setText:@"错误"];
		NSString* strRAnswer = [[NSString alloc] init];
		if([[arrayOfQuestion objectAtIndex:1] isEqualToString:@"C"])
		{
			strRAnswer = @"正确";
		}
		else if([[arrayOfQuestion objectAtIndex:1] isEqualToString:@"D"])
		{
			strRAnswer = @"错误";
		}
		[m_pRightAnswerLabel setText:[@"正确答案:" stringByAppendingString:strRAnswer]];
		[strRAnswer release];
		
		NSString* strPChoose;
		if([[arrayOfQuestion objectAtIndex:([arrayOfQuestion count]-1)] isEqualToString:@"C"])
		{
			strPChoose = @"正确";
		}
		else if([[arrayOfQuestion objectAtIndex:([arrayOfQuestion count]-1)] isEqualToString:@"D"])
		{
			strPChoose = @"错误";
		}
		else if([[arrayOfQuestion objectAtIndex:([arrayOfQuestion count]-1)] isEqualToString:@"没选"])
		{
			strPChoose = @"没选";
		}
		[m_pPrevChooseLabel setText:[@"上次所选:" stringByAppendingString:strPChoose]];
		
		m_pImageView.alpha = 0.f;
		
		if(4 == [arrayOfQuestion count])
		{
			m_pImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[arrayOfQuestion objectAtIndex:2]]];
			
			float fWidth = m_pImageView.frame.size.width;
			float fHeight = m_pImageView.frame.size.height;
			m_pImageView.alpha = 1.f;
			
			[m_pImageView setFrame:CGRectMake((320 - fWidth)/2, m_pQuestionLabel.frame.size.height + 50, fWidth, fHeight)];
			[self.view addSubview:m_pImageView];
			[m_pImageView release];
		}		
	}
}

#pragma mark -
#pragma mark Prev page button handle
- (IBAction)prevPage:(id)sender
{
	m_nCurQuestionNumber--;
	if(m_nCurQuestionNumber < 0)
	{
		m_nCurQuestionNumber++;
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:TITLE_ALERT_FIRSTQUESTION
															message:nil
														   delegate:self 
												  cancelButtonTitle:@"哦,知道了" 
												  otherButtonTitles: nil];
		[alertView show];
		[alertView release];
		return;
	}
	
	// View flip
	[self viewFlip:@"Down"];	
	
	// Get question
	[self getQuestion:m_nCurQuestionNumber];
}

#pragma mark -
#pragma mark Next page button handle
- (IBAction)nextPage:(id)sender
{
	m_nCurQuestionNumber++;
	if(m_nCurQuestionNumber > ([m_arrayOfWrongQuestion count]-1))
	{
		m_nCurQuestionNumber--;
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:TITLE_ALERT_LASTQUESTION
															message:nil
														   delegate:self 
												  cancelButtonTitle:@"哦,知道了" 
												  otherButtonTitles: nil];
		[alertView show];
		[alertView release];
		return;
	}
	
	// View flip
	[self viewFlip:@"Up"];
	
	// Get question
	[self getQuestion:m_nCurQuestionNumber];
}

#pragma mark -
#pragma mark Strengthening memory button handle
- (IBAction)strengtheningMemory:(id)sender
{
	NSArray* arrayOfFilePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString* strFilePath = [[arrayOfFilePath objectAtIndex:0] stringByAppendingPathComponent:PLIST_STRENGTHENINGMEMORY];
	NSMutableArray* _tempArrayOfStrengtheningMemory = [[NSMutableArray alloc] initWithContentsOfFile:strFilePath];
	[m_arrayOfStrengtheningMemory removeAllObjects];
	[m_arrayOfStrengtheningMemory addObjectsFromArray:_tempArrayOfStrengtheningMemory];
	
	// One question
	NSMutableArray* arrayOfQuestion = [m_arrayOfWrongQuestion objectAtIndex:m_nCurQuestionNumber];
	
	if([m_arrayOfStrengtheningMemory count] <= 0)
	{		
		// Strengthening memory array
		[m_arrayOfStrengtheningMemory addObject:arrayOfQuestion];
		
		[m_arrayOfStrengtheningMemory writeToFile:strFilePath atomically:YES];
		
		// Write file name to file 
		WriteFile* writeFile = [[WriteFile alloc] init];
		[writeFile WriteString:strFilePath];
		[writeFile CloseFile:FILE_STRENGTHENINGMEMORY];
		[writeFile release];
	}
	else if([m_arrayOfStrengtheningMemory count] > 0)
	{
		for(int i = 0; i < [m_arrayOfStrengtheningMemory count]; i++)
		{
			if([[[m_arrayOfStrengtheningMemory objectAtIndex:i] objectAtIndex:0] isEqualToString:[arrayOfQuestion objectAtIndex:0]])
			{
				UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:TITLE_ALERT_HASBEENADDED
																	message:nil
																   delegate:self 
														  cancelButtonTitle:@"好的" 
														  otherButtonTitles:nil];
				[alertView show];
				[alertView release];			
				return;
			}
		}
		// Strengthening memory array
		[m_arrayOfStrengtheningMemory addObject:arrayOfQuestion];
		
		[m_arrayOfStrengtheningMemory writeToFile:strFilePath atomically:YES];
		
		// Write file name to file 
		WriteFile* writeFile = [[WriteFile alloc] init];
		[writeFile WriteString:strFilePath];
		[writeFile CloseFile:FILE_STRENGTHENINGMEMORY];
		[writeFile release];
	}
}

#pragma mark -
#pragma mark View flip
- (void)viewFlip:(NSString*)flipMode
{
	[UIView beginAnimations:@"View Flip" context:nil];
	[UIView setAnimationDuration:1.f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	
	if([flipMode isEqualToString:@"Up"])
	{
		[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES];
	}
	else if([flipMode isEqualToString:@"Down"])
	{
		[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:YES];
	}
	[self viewWillAppear:YES];
	[UIView commitAnimations];
	
	// Play effect
	NSString* effectPath = [[NSBundle mainBundle] pathForResource:@"FlipPage" ofType:@"caf"];
	SystemSoundID soundID;
	AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:effectPath], &soundID);
	AudioServicesPlaySystemSound(soundID);
}

#pragma mark -
#pragma mark No wrong question
- (void)noWrongQuestion
{
	// Set title
	[self.navigationController.visibleViewController setTitle:@"没有错题记录"];
	m_pPrevButton.hidden = YES;
	m_pNextButton.hidden = YES;
	m_pStrengtheningMemoryButton.hidden = YES;
	
	
	// Alert
	UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"暂时没有错题记录"
														message:nil
													   delegate:self 
											  cancelButtonTitle:@"哦,知道了" 
											  otherButtonTitles:nil];
	[alertView show];
	[alertView release];	
}

#pragma mark -
#pragma mark - Add label text
- (void)addLabelText:(UILabel*)label labelText:(NSString*)labelText
{
	label.text = labelText;
	
	CGSize size = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(300, 500) lineBreakMode:UILineBreakModeCharacterWrap];
	
	label.frame = CGRectMake(15, 10, size.width, size.height);
}

#pragma mark -
#pragma mark - alertView:clickedButtonAtIndex:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([alertView.title isEqualToString:@"暂时没有错题记录"])
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

/*
- (IBAction)RefreshButtonHandle:(id)sender
{
	// Init data
	[m_arrayOfStrengtheningMemory removeAllObjects];
	[m_arrayOfWrongQuestion release];
	[m_arrayOfWrongQuestion removeAllObjects];

	
	ReadFile* readFile = [[ReadFile alloc] init];
	BOOL bIsFileCanBeOpened = [readFile OpenFile:@"WrongQuestion.sg"];
	if(bIsFileCanBeOpened)
	{
		// Get file path
		NSString* strFilePath = [readFile ReadString];
		
		m_arrayOfWrongQuestion = [[NSMutableArray alloc] initWithContentsOfFile:strFilePath];	
		
		NSLog(@"%d\n",[m_arrayOfWrongQuestion count]);
		
		[readFile CloseFile];
		[readFile release];
		
		// Get one question
		[self getQuestion:m_nCurQuestionNumber];
		
	}
	else
	{
		UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"暂时没有错题记录"
															message:nil
														   delegate:self 
												  cancelButtonTitle:@"哦,知道了" 
												  otherButtonTitles:nil];
		[alertView show];
		[alertView release];
	}
}
*/
#pragma mark -
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return NO;//(interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc 
{
	[m_arrayOfWrongQuestion release];
	[m_arrayOfStrengtheningMemory release];
	
    [super dealloc];
}


@end
